package com.encryption.dao;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.encryption.logic.impl.FileConditionSqlParser;
import com.encryption.model.File;
import com.encryption.model.User;

/**
 * A data access object (DAO) providing persistence and search support for File
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.encryption.model.File
 * @author MyEclipse Persistence Tools
 */

public class FileDAO extends BaseHibernateDAO {
	private static final Logger log = LoggerFactory.getLogger(FileDAO.class);
	// property constants
	public static final String NAME = "name";
	public static final String TYPE = "type";
	public static final String TAG = "tag";
	public static final String SIZE = "size";
	private static final int DELETE_CATEGARY = -3;

	public void save(File transientInstance) {
		log.debug("saving File instance");
		try {
			getSession().save(transientInstance);
			getSession().flush();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(File persistentInstance) {
		log.debug("deleting File instance");
		try {
			FilePermissionAssoDAO.getFilePermissionAssoDAO().deleteByFileId(persistentInstance.getId());
			
			String deleteSql = "update file set category="+ DELETE_CATEGARY +" where id=" + persistentInstance.getId();
			SQLQuery query = getSession().createSQLQuery(deleteSql);
			query.executeUpdate();
			flush(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public File findById(java.lang.Integer id) {
		log.debug("getting File instance with id: " + id);
		try {
			File instance = (File) getSession().get(
					"com.encryption.model.File", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public int findCurrentMaxId(){
		int fid = (Integer)getSession().createQuery("select max(f.id) from File f").uniqueResult();
		return fid;
	}

	public List findByExample(File instance) {
		log.debug("finding File instance by example");
		try {
			List results = getSession()
					.createCriteria("com.encryption.model.File")
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding File instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from File as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findByType(Object type) {
		return findByProperty(TYPE, type);
	}

	public List findByTag(Object tag) {
		return findByProperty(TAG, tag);
	}

	public List findBySize(Object size) {
		return findByProperty(SIZE, size);
	}

	public List findAll() {
		log.debug("finding all File instances");
		try {
			String queryString = "from File";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public File merge(File detachedInstance) {
		log.debug("merging File instance");
		try {
			File result = (File) getSession().merge(detachedInstance);
			flush(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(File instance) {
		log.debug("attaching dirty File instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(File instance) {
		log.debug("attaching clean File instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	/**
	 * 根据condition对文件表查询
	 * @param instance
	 * @return
	 */
	public  List<File> findByExample(List<Condition> conditions) {
		log.debug("finding File instance by example");
		try {
			 
			Criteria criteria= getSession()
					.createCriteria(File.class);
			
			//设置查询条件
			BaseHibernateDAO.addCriteria(conditions, criteria);
			
			 List<File> results = criteria.list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	/**
	 * 分页查询文件表
	 */
	public List<File> findByExample4Page(List<Condition> conditions, int page, int pageSize) {
			log.debug("finding File instance by example");
			try {
				Criteria criteria= getSession()
					.createCriteria(File.class);
				//设置查询条件
				BaseHibernateDAO.addCriteria(conditions, criteria);
				criteria.setFirstResult(page);
				criteria.setFetchSize(pageSize);
				List<File> results =criteria.list();
				
				log.debug("find by example successful, result size: "
						+ results.size());
				return results;
			} catch (RuntimeException re) {
				log.error("find by example failed", re);
				throw re;
			}
		}
	
	/**
	 * 分页查询文件表
	 */
	public List<File> findPagingByCondition(User user, List<Condition> conditions, int page, int pageSize) {
		try {
			int deptId = user.getDepartment();
			int userId = user.getId();
			int fileLevel = user.getFileLevel();
			int startIndex = page * pageSize;
			conditions.add(createDeleteCondition());
			String condSql = FileConditionSqlParser.parse(user, conditions);
			
			String sql = "select * from file where ( (level<=" + fileLevel + ") or (upload_user=" + userId + ") " +
					"or ( id in (select distinct file_id from file_permission_asso where " +
					"(allow_type=0 or (allow_type=2 and allow_value="+ deptId +") or (allow_type=1 and allow_value="+ userId +") ) ) " +
							") )" + condSql + "order by upload_time desc" +" limit "+ startIndex +", "+ pageSize +"";
			
			Query query = getSession().createSQLQuery(sql).addEntity(File.class);
			List<File> results = query.list();
			
			log.debug("执行语句:" + sql);
			return results;
		} catch (RuntimeException re) {
			log.error("findPagingByCondition failed", re);
			throw re;
		}
	}
	
	private Condition createDeleteCondition(){
		Condition cond = new Condition();
		cond.setCode("category");
		cond.setOperation("!=");
		cond.setValue(-3);
		
		return cond;
	} 
	
	/**
	 * 分页查询文件表
	 */
	public List<File> findPagingByCondition(List<Condition> conditions, int page, int pageSize) {
		try {
			int startIndex = page * pageSize;
			conditions.add(createDeleteCondition());
			String condSql = FileConditionSqlParser.parse(conditions);
			
			String sql = "select * from file where  "+ condSql +" order by upload_time desc limit "+ startIndex +", "+ pageSize +"";
			
			Query query = getSession().createSQLQuery(sql).addEntity(File.class);
			List<File> results = query.list();
			
			log.debug("执行语句:" + sql);
			return results;
		} catch (RuntimeException re) {
			log.error("findPagingByCondition failed", re);
			throw re;
		}
	}
	
	/**
	 * 分页查询文件表
	 */
	public int findTotalCountByCondition(User user, List<Condition> conditions) {
		log.debug("finding File instance by example");
		try {
			conditions.add(createDeleteCondition());
			int deptId = user.getDepartment();
			int userId = user.getId();
			int fileLevel = user.getFileLevel();
			String condSql = FileConditionSqlParser.parse(user, conditions);
			
			String sql = "select count(*) from file where ( (level <=" + fileLevel + ") or (upload_user=" + userId + ") " +
					"or (id in (select distinct file_id from file_permission_asso where " +
			"(allow_type=0 or (allow_type=2 and allow_value="+ deptId +") or (allow_type=1 and allow_value="+ userId +") ) )" + 
				") )" + condSql;
			
			Query query = getSession().createSQLQuery(sql);
			int totalCount = ((BigInteger) query.list().get(0)).intValue();
			
			log.debug("执行语句:" + sql);
			return totalCount;
		} catch (RuntimeException re) {
			log.error("findTotalCountByCondition failed", re);
			throw re;
		}
	}
	

	private void flush(File file)
	{
		try{
			getSession().flush();
		}catch (Exception e) {
			log.debug("",e);
		}
		getSession().evict(file);
	}
	
	private static FileDAO fileDAO = null;
	
	
	public static  FileDAO getFileDAO(){
		if(null == fileDAO) {
			fileDAO = new FileDAO();
		} 
		return fileDAO;
	}
	
}